import React, { useEffect, useCallback } from 'react';
import * as ReactDOM from 'react-dom';
import 'antd-mobile/es/global';
import './styles.less';

import { HashRouter } from 'react-router-dom';
import Router from './router';
import Store from './store';
import { browser } from 'webextension-polyfill-ts';
import {  storage } from './utils';

const Popup = () => {
    const { setStore } = Store.useContainer();
  
    const onChanges = useCallback((changes) => {
        if (changes.vpnStore) {
            const { newValue } = changes.vpnStore;
            //console.log("vpnStore to store",newValue)
            setStore(newValue);
        }
    }, []);

    useEffect(() => {
        //chrome
        browser.storage.onChanged.addListener(onChanges);
        //获取节点列表,先判断是否登录，如果未登录使用游客登录

        storage.get('vpnStore').then((result) => {
            if (result.vpnStore) {
                setStore(result.vpnStore);
            }
        });
        //更新个人信息
      
        return () => {
            browser.storage.onChanged.removeListener(onChanges);
        };
    }, []);

    return (
        <HashRouter>
            <Router />
        </HashRouter>
    );
};

const App: React.FC = () => {
    return (
        <Store.Provider>
            <Popup />
        </Store.Provider>
    );
};

ReactDOM.render(<App />, document.getElementById('popup-root'));
